import { toSrcset } from 'mini-svg-data-uri';

// 提取 url 中顶级域名
// eg: https://www.example.com/path/to/page => example.com
// eg: https://space.bilibili.com/xxxxx => bilibili.com
export const extractDomainFromUrl = (urlString: string) => {
    try {
        // 检查是否是相对链接或无效URL
        if (!urlString || typeof urlString !== 'string') {
            return '';
        }

        // 如果是相对链接（不以http开头），返回空字符串
        if (!urlString.startsWith('http://') && !urlString.startsWith('https://')) {
            return '';
        }

        const url = new URL(urlString);
        const hostnameParts = url.hostname.split('.');
        if (hostnameParts.length >= 2) {
            return hostnameParts.slice(-2).join('.');
        } else {
            return url.hostname;
        }
    } catch (error) {
        // 如果URL构造失败，返回空字符串
        console.warn('Failed to parse URL:', urlString, error);
        return '';
    }
};

export const convertSvgToDataUrl = (svgString?: string) => {
    if (!svgString) {
        return '';
    }

    if (!svgString?.startsWith('<svg')) {
        return svgString;
    }

    return toSrcset(svgString);
};
